const crypto = require('crypto');
const http = require('https');
const querystring = require('querystring');
// const Access  = {
//     key:"90456573fefdfb349603e6c3db9f160f",
//     Secret:"99205845c9de"
// };
const Access  = {
    key:"88bdec1363428e5f4e8698f05d030b0b",
    Secret:"0982d518d123"
};
let sha1 = (str)=>{
    let sha1 = crypto.createHash("sha1");//定义加密方式:md5不可逆,此处的md5可以换成任意hash加密的方法名称；
    sha1.update(str);
    let res = sha1.digest("hex");  //加密后的值
    return res;
};
const createHeader = ()=>{
    let opt = {
        AppKey:Access.key,
        Nonce:new Date().getTime()+'',
        CurTime:new Date().getTime()+'',
    };
    return {
        'Content-Type': 'application/x-www-form-urlencoded',
        'AppKey':Access.key,
        'Nonce':new Date().getTime()+'',
        'CurTime':new Date().getTime()+'',
        'CheckSum':sha1(Access.Secret+opt.Nonce+opt.CurTime)
    }
};
module.exports = {
    validByShortMsg(userTelNumber){
        return new Promise((resolve, reject)=>{
            const req = http.request({
                hostname:'api.netease.im',
                port:443,
                path:'/sms/sendcode.action',
                method:'POST',
                headers:createHeader()
            },(res)=>{
                let str = '';
                res.on('data',(data)=>{
                    str += data;
                });
                res.on('end', ()=>{
                    resolve(JSON.parse(str)['obj'])
                });
                res.on("error",(error)=>{
                    reject(error);
                })
            });
            req.on('error',(error)=>{
                reject(error);
            });
            req.write(querystring.stringify({mobile:userTelNumber}));
            req.end();
        });
    }
};